package org.yunai.swjg.server.module.battle.operation;

import org.yunai.swjg.server.core.service.Online;
import org.yunai.swjg.server.module.battle.unit.BattleTeam;
import org.yunai.swjg.server.module.battle.unit.BattleUnit;
import org.yunai.swjg.server.module.player.vo.AbstractRole;
import org.yunai.yfserver.async.IIoOperation;
import org.yunai.yfserver.util.MathUtils;

/**
 * 基础战斗操作
 * User: yunai
 * Date: 13-5-17
 * Time: 下午9:41
 */
public abstract class BaseBattleOperation implements IIoOperation {

    /**
     * 进攻队伍
     */
    protected BattleTeam attackTeam;
    /**
     * 防守队伍
     */
    protected BattleTeam defenseTeam;

    public BaseBattleOperation(Online online, boolean attackIsFullHp) {
        attackTeam = new BattleTeam();
        // TODO 精简版（不带宠物）
        AbstractRole role = online.getPlayer();
        addBattleUnit(role, true, attackIsFullHp);
    }

    protected void addBattleUnit(AbstractRole role, boolean isAttack, boolean isFullHp) {
        // 构建战斗单元
        BattleUnit unit = BattleUnit.getInstance(role, isAttack, isFullHp);
        // 加入队伍
        if (isAttack) {
            attackTeam.addUnit(unit);
        } else {
            defenseTeam.addUnit(unit);
        }
    }

    private void battle() {
        // TODO 战斗（隐藏模式 哟哟）
        boolean attWin = MathUtils.nextBoolean();
        defenseTeam.getUnits().get(0).setHpCur(defenseTeam.getUnits().get(0) .getHpCur()
                - attackTeam.getUnits().get(0).getHpCur());
        if (defenseTeam.getUnits().get(0).getHpCur() < 0) {
            defenseTeam.getUnits().get(0).setHpCur(0);
        }
        endImpl(attWin);
    }

    @Override
    public State doStart() {
        return State.STARTED;
    }

    @Override
    public State doIo() {
        try {
            battle();
        } catch (Exception e) {
            // TODO log
            e.printStackTrace();
        }
        return State.IO_DONE;
    }

    /**
     * 战斗结束子类拓展实现
     *
     * @param attWin 攻击方是否胜利
     */
    protected abstract void endImpl(boolean attWin);

    @Override
    public State doFinish() {
        return State.FINISHED;
    }
}
